package cn.iocoder.yudao.module.member.service.auth;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.enums.TerminalEnum;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.util.monitor.TracerUtils;
import cn.iocoder.yudao.framework.common.util.servlet.ServletUtils;
import cn.iocoder.yudao.module.member.controller.app.auth.vo.*;
import cn.iocoder.yudao.module.member.convert.auth.AuthConvert;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
import cn.iocoder.yudao.module.member.service.user.MemberUserService;
import cn.iocoder.yudao.module.system.api.logger.LoginLogApi;
import cn.iocoder.yudao.module.system.api.logger.dto.LoginLogCreateReqDTO;
import cn.iocoder.yudao.module.system.api.oauth2.OAuth2TokenApi;
import cn.iocoder.yudao.module.system.api.oauth2.dto.OAuth2AccessTokenCreateReqDTO;
import cn.iocoder.yudao.module.system.api.oauth2.dto.OAuth2AccessTokenRespDTO;
import cn.iocoder.yudao.module.system.api.sms.SmsCodeApi;
import cn.iocoder.yudao.module.system.api.social.SocialClientApi;
import cn.iocoder.yudao.module.system.api.social.SocialUserApi;
import cn.iocoder.yudao.module.system.api.social.dto.SocialUserBindReqDTO;
import cn.iocoder.yudao.module.system.api.social.dto.SocialUserRespDTO;
import cn.iocoder.yudao.module.system.api.social.dto.SocialWxPhoneNumberInfoRespDTO;
import cn.iocoder.yudao.module.system.enums.logger.LoginLogTypeEnum;
import cn.iocoder.yudao.module.system.enums.logger.LoginResultEnum;
import cn.iocoder.yudao.module.system.enums.oauth2.OAuth2ClientConstants;
import cn.iocoder.yudao.module.system.enums.sms.SmsSceneEnum;
import cn.iocoder.yudao.module.system.enums.social.SocialTypeEnum;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpPost;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.aliyun.tea.TeaException;
import com.douyin.openapi.client.Client;
import com.douyin.openapi.client.models.*;
import com.douyin.openapi.credential.models.Config;



import javax.annotation.Resource;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.net.URI;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.net.URI;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.servlet.ServletUtils.getClientIP;
import static cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils.getTerminal;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.*;

/**
 * 会员的认证 Service 接口
 *
 * @author 芋道源码
 */
@Service
@Slf4j
public class MemberAuthServiceImpl implements MemberAuthService {

    @Resource
    private MemberUserService userService;
    @Resource
    private SmsCodeApi smsCodeApi;
    @Resource
    private LoginLogApi loginLogApi;
    @Resource
    private SocialUserApi socialUserApi;
    @Resource
    private SocialClientApi socialClientApi;
    @Resource
    private OAuth2TokenApi oauth2TokenApi;

    @Override
    public AppAuthLoginRespVO login(AppAuthLoginReqVO reqVO) {
        // 使用手机 + 密码，进行登录。
        MemberUserDO user = login0(reqVO.getMobile(), reqVO.getPassword());

        // 如果 socialType 非空，说明需要绑定社交用户
        String openid = null;
        if (reqVO.getSocialType() != null) {
            openid = socialUserApi.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(),
                    reqVO.getSocialType(), reqVO.getSocialCode(), reqVO.getSocialState()));
        }

        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user, reqVO.getMobile(), LoginLogTypeEnum.LOGIN_MOBILE, openid);
    }

    @Override
    @Transactional
    public AppAuthLoginRespVO smsLogin(AppAuthSmsLoginReqVO reqVO) {
        // 校验验证码
        String userIp = getClientIP();
        smsCodeApi.useSmsCode(AuthConvert.INSTANCE.convert(reqVO, SmsSceneEnum.MEMBER_LOGIN.getScene(), userIp));

        // 获得获得注册用户
        MemberUserDO user = userService.createUserIfAbsent(reqVO.getMobile(), userIp, getTerminal());
        Assert.notNull(user, "获取用户失败，结果为空");

        // 如果 socialType 非空，说明需要绑定社交用户
        String openid = null;
        if (reqVO.getSocialType() != null) {
            openid = socialUserApi.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(),
                    reqVO.getSocialType(), reqVO.getSocialCode(), reqVO.getSocialState()));
        }

        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user, reqVO.getMobile(), LoginLogTypeEnum.LOGIN_SMS, openid);
    }

    @Override
    @Transactional
    public AppAuthLoginRespVO socialLogin(AppAuthSocialLoginReqVO reqVO) {
        // 使用 code 授权码，进行登录。然后，获得到绑定的用户编号
        SocialUserRespDTO socialUser = socialUserApi.getSocialUserByCode(UserTypeEnum.MEMBER.getValue(), reqVO.getType(),
                reqVO.getCode(), reqVO.getState());
        if (socialUser == null) {
            throw exception(AUTH_SOCIAL_USER_NOT_FOUND);
        }

        // 情况一：已绑定，直接读取用户信息
        MemberUserDO user;
        if (socialUser.getUserId() != null) {
            user = userService.getUser(socialUser.getUserId());
        // 情况二：未绑定，注册用户 + 绑定用户
        } else {
            user = userService.createUser(socialUser.getNickname(), socialUser.getAvatar(), getClientIP(), getTerminal());
            socialUserApi.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(),
                    reqVO.getType(), reqVO.getCode(), reqVO.getState()));
        }
        if (user == null) {
            throw exception(USER_NOT_EXISTS);
        }

        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user, user.getMobile(), LoginLogTypeEnum.LOGIN_SOCIAL, socialUser.getOpenid());
    }

    @Override
    public AppAuthLoginRespVO weixinMiniAppLogin(AppAuthWeixinMiniAppLoginReqVO reqVO) {
        // 获得对应的手机号信息
        SocialWxPhoneNumberInfoRespDTO phoneNumberInfo = socialClientApi.getWxMaPhoneNumberInfo(
                UserTypeEnum.MEMBER.getValue(), reqVO.getPhoneCode());
        Assert.notNull(phoneNumberInfo, "获得手机信息失败，结果为空");

        // 获得获得注册用户
        MemberUserDO user = userService.createUserIfAbsent(phoneNumberInfo.getPurePhoneNumber(),
                getClientIP(), TerminalEnum.WECHAT_MINI_PROGRAM.getTerminal());
        Assert.notNull(user, "获取用户失败，结果为空");

        // 绑定社交用户
        String openid = socialUserApi.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(),
                SocialTypeEnum.WECHAT_MINI_APP.getType(), reqVO.getLoginCode(), reqVO.getState()));

        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user, user.getMobile(), LoginLogTypeEnum.LOGIN_SOCIAL, openid);
    }




    /**
     * 抖音小程序手机号登录
     *
     * @param reqVO 登录信息
     * @return 登录结果
     */
    @Override
    public AppAuthLoginRespVO douyinMiniAppLogin(AppAuthDouyinMiniAppLoginReqVO reqVO) throws InvalidAlgorithmParameterException, NoSuchPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException, BadPaddingException, InvalidKeyException {
        //通过code 来进行登录，
        V2Jscode2sessionResponse data = code2Session(reqVO.getLoginCode(), reqVO.getAnonymousCode());

    /*    OauthAccessTokenResponseData data = createDoubyinMiniAppLogin(reqVO);
        if (data.errorCode != 0) {
            data.description = data.description + "(" + data.errorCode + ")";
            throw exception(AUTH_DOUYIN_MINI_APP_LOGIN_FAIL, data.description);
        }*/
        log.info("抖音小程序手机号登录信息成功，结果为{}", data);
        Assert.notNull(data, "抖音小程序手机号登录信息失败，结果为空");
       /* String accessToken = data.accessToken;
        String openId = data.openId;*/
        String sessionKey = data.getData().sessionKey;


        String decryptedData = decrypt(reqVO.getEncryptedData(), sessionKey, reqVO.getIv());
     /*   String str = getPhoneNumber(reqVO.getLoginCode(), null);
        String decryptedData = decryptData(str);
*/
        log.info("抖音小程序手机号信息，结果为{}", decryptedData);
        JSONObject o = JSON.parseObject(decryptedData);
        String purePhoneNumber = o.getString("purePhoneNumber");
        // 获得获得注册用户
        MemberUserDO user = userService.createUserIfAbsent(purePhoneNumber,
                getClientIP(), TerminalEnum.DY_MINI_PROGRAM.getTerminal());
        Assert.notNull(user, "获取用户失败，结果为空");

        // 绑定社交用户
        String openid = socialUserApi.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(),
                SocialTypeEnum.DY_MINI_APP.getType(), reqVO.getLoginCode(), null));

        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user, user.getMobile(), LoginLogTypeEnum.LOGIN_SOCIAL, openid);
    }

    @Override
    public OauthAccessTokenResponseData douyinMiniAppLogin1(AppAuthDouyinMiniAppLoginReqVO reqVO) {
        //通过code 来进行登录，
        OauthAccessTokenResponseData data = createDoubyinMiniAppLogin(reqVO);
     /*   if (data.errorCode != 0) {
            data.description = data.description + "(" + data.errorCode + ")";
            throw exception(AUTH_DOUYIN_MINI_APP_LOGIN_FAIL,data.description);
        }
        String accessToken = data.accessToken;
        String openId = data.openId;
        //获取用户信息

        //判断用户信息在系统内是否存在，不存在就新增，存在就自己用原来的。

        //生产openId  给小程序
*/
        return data;
    }


    @Override
    public V2Jscode2sessionResponse douyinMiniAppLogin2(AppAuthDouyinMiniAppLoginReqVO reqVO) {
        //通过code 来进行登录，
        V2Jscode2sessionResponse data = code2Session(reqVO.getLoginCode(),reqVO.getAnonymousCode());
     /*   if (data.errorCode != 0) {
            data.description = data.description + "(" + data.errorCode + ")";
            throw exception(AUTH_DOUYIN_MINI_APP_LOGIN_FAIL,data.description);
        }
        String accessToken = data.accessToken;
        String openId = data.openId;
        //获取用户信息

        //判断用户信息在系统内是否存在，不存在就新增，存在就自己用原来的。

        //生产openId  给小程序
*/


        return data;
    }

    @Override
    public String douyinMiniAppLogin3(AppAuthDouyinMiniAppLoginReqVO reqVO) {
        OauthAccessTokenResponseData data = createDoubyinMiniAppLogin(reqVO);
        String accessToken = data.accessToken;
        String str = getPhoneNumber(reqVO.getPhoneNumberCode(), accessToken);
        String decryptedData = decryptData(str);
        return decryptedData;
    }

    public String getPhoneNumber(String phoneNumberCode,String token) {


     /*   {
            "code": "\"RWRwy7BZiOaEqEPjZ6j7NdgbBLEDNMLKC6gpnlMrM718yfUaM5FumPOIyq/hk06yZjkSEfdQZ8nL9OWP2ez6z/3kX8wU5dF10wCw7gl+zZ9ZyIA7QOpojPxPLs1kxZBr7uOyMivU6g+ZnfgP\""
        }*/

        Map<String, Object> params = new HashMap<>();
        params.put("code", phoneNumberCode);
        String jsonString = JSON.toJSONString(params);
        String url = "https://open.douyin.com/api/apps/v1/get_phonenumber_info/";
        HttpRequest post = HttpUtil.createPost(url);
        post.header("access-token", token);
        post.header("content-type", "application/json");
        post.body(jsonString);
        HttpResponse response = post.execute();
        String result = response.body();

        return result;
    }


    public  String decrypt(String encryptedData, String sessionKey, String iv) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IllegalBlockSizeException {
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] sessionKeyBytes = decoder.decode(sessionKey);
        byte[] ivBytes = decoder.decode(iv);
        byte[] encryptedBytes = decoder.decode(encryptedData);

        // JDK does not support PKCS7Padding, use PKCS5Padding instead
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec skeySpec = new SecretKeySpec(sessionKeyBytes, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
        byte[] ret = cipher.doFinal(encryptedBytes);
        return new String(ret);
    }

    public String decryptData(String encryptedData) {
        try {
            String privateKeyString = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDjNR5NKlsPofE7\n" +
                    "k1xUy7ldd/nAus4r7zTBpCH0+2ywdfPD6IhdvO5AFmtwJy5JnCoJ2c5xOyM3RHOe\n" +
                    "3Ju2zLZ8A8EbUWmCtVJzNXPYQAyQeyCcKbHQxR8LC6JWI/iD12QbGojapXrBq9x/\n" +
                    "iu8x2UfM4eVEN+o2LZOvX0RYSSnfnyKSNVCcvFTe3mwZR/WOWB/8zT1TX6zJrVQb\n" +
                    "42+UJ0H257W9Xou8Bnok5ZSgZFkJvQQ2gFv3I0hzAiQd6+S8YSIS0gz9p6Luo4Jg\n" +
                    "xqXpkztGioXSFg7oFm3SqnjdXvquyAUuyvta/kGSmvTl38vqXonjFuEBBJY0lPZB\n" +
                    "Le0iQJRvAgMBAAECggEBAL/TIgEeSIFbRVL6KBMDaT3LxFX+oYCgVZdDXtP5zhrx\n" +
                    "itwVH8ScdT4wb4bh3YeSTD/C3zPkLOhFZ6RxNxpPnaX4eXn58y3CrpjMQUELWlBF\n" +
                    "VBPkc9cCBiKKMQWvGusc18y2S2LmIU0QL3qTLz2T57XH5owA9UHGmxCOSyKKqsq7\n" +
                    "ddtgnCtqw6bC0h/7tlt3ijJkUOvo7NyIql6yjrjhRyqT5gz5IYN8HYBViIAR2Bqm\n" +
                    "7WHredlUrPm0nreKJt8thDDcfHi8gGZZeILmvSYfTdxQ8kfuCHetlf7kaJvF8XvL\n" +
                    "EMXaI94C/Zm0ZUleOLgU5WqhmqGJ4eOGBu797npT/4kCgYEA9oIEEiJkLrq8L5c4\n" +
                    "25czSBrmQ8pxAG2qXne19A3ltgdokMPNzYKFRC1zTy6/PHK7WXTtGqhCiOnGazwk\n" +
                    "vOtvQQPZwvqn91caQFozWPPglpiNklq/H5AMW5PuhH2nzbDuW0swanuUwEAhRzZw\n" +
                    "pLYt0e9aAQxyIHaLbi4FAOI7qDsCgYEA6/TYrV2tdwzrXTz821U6dfaXKabLM5A5\n" +
                    "39HzMFMbnLGxYNTCV/seuOefdgWA5J98szlF9AiqUXluK3dRc0pAIinmFgxXE8kz\n" +
                    "JErzxr/B9S5uSw84BtghGsBYQGFoBoywFxDTV2m6X1hXjB1zPiRDKbTUFMXrMFcG\n" +
                    "LNFU7zp89V0CgYEAmNHvniJuAz5G7iYM3K224Au1Fu/I8GAMT7ZdOejnsNqU67JH\n" +
                    "wxEYdzTKGJu9eMcT+JhxaaZIYUK0fMRzbh9zAFZXyPXF7aO1JZIF5S6D3DjFA6d4\n" +
                    "dyPBVYC3TLHttqnqivRpFop4pFrdhp1sZeB/NXfyT1Yc5p03QV4MQgj+vQMCgYAo\n" +
                    "+q8e/OQBhxbhbJQlq5mpnxgFvdgQrn2+p4Hq5KQpBJtfy9Os4Aon5uJE5xPJoQFR\n" +
                    "RyMlDNQ3rjU6C1D0CvM0e75gGeiNoSXmqbXI0MjowhWZp5z9Y0/si3dIRyJ/8LMs\n" +
                    "blmmFtCtenRJ+1tmcXnQpn0m1nDQRmzmH7z2h1voaQKBgExc5iESmpiyIv0HBzw/\n" +
                    "zLYeg9atwqZQaZLLWTihTEEKYjqOI+Me2WrzZ1753IE37m7UugXqDK5JRnEXrK6a\n" +
                    "FAfxohZeI5QcIIT/Nc3J8mbKApxHafzvg88RhGdFKJ/oiVu5gbqtBqjfbLDoHUzw\n" +
                    "VnjeaO5qgjU8R+TMY7fgr8Sb";

                    // Decrypt the data
            String decryptedData = decrypt(encryptedData, privateKeyString);
            System.out.println("Decrypted Data: " + decryptedData);

            return decryptedData;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    public static String decrypt(String encryptedData, String privateKeyString) throws Exception {
        // Decode the private key
        byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyString);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

        // Decrypt the data
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedDataBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(decryptedDataBytes);
    }

    /**
     * 通过code获取token
     * @param reqVO
     * @return
     */
    private OauthAccessTokenResponseData createDoubyinMiniAppLogin(AppAuthDouyinMiniAppLoginReqVO reqVO) {
        try {
            Config config = new Config().setClientKey("tt767a00c7e971e78301")
                    .setClientSecret("9a05aacc286beaa774ca7d7f4febc33d25359a0d"); // 改成自己的app_id跟secret
            Client client = new Client(config);
            /* 构建请求参数，该代码示例中只给出部分参数，请用户根据需要自行构建参数值
                token:
                   1.若用户自行维护token,将用户维护的token赋值给该参数即可
                   2.SDK包中有获取token的函数，请根据接口path在《OpenAPI SDK 总览》文档中查找获取token函数的名字
                     在使用过程中，请注意token互刷问题
                header:
                   sdk中默认填充content-type请求头，若不需要填充除content-type之外的请求头，删除该参数即可
            */
            OauthAccessTokenRequest sdkRequest = new OauthAccessTokenRequest();
            sdkRequest.setClientKey("tt767a00c7e971e78301");
            sdkRequest.setClientSecret("9a05aacc286beaa774ca7d7f4febc33d25359a0d");
            sdkRequest.setCode(reqVO.getLoginCode());
            sdkRequest.setGrantType("authorization_code");
            OauthAccessTokenResponse sdkResponse = client.OauthAccessToken(sdkRequest);
            OauthAccessTokenResponseData data = sdkResponse.data;
            return data;
        } catch (TeaException e) {
            System.out.println(e.getMessage());
            return null;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }
    }

    /**
     * code2Session
     */
    private V2Jscode2sessionResponse code2Session(String code,String anonymousCode){
        try {
            Config config = new Config().setClientKey("tt767a00c7e971e78301")
                    .setClientSecret("9a05aacc286beaa774ca7d7f4febc33d25359a0d"); // 改成自己的app_id跟secret
            Client client = new Client(config);
            /* 构建请求参数，该代码示例中只给出部分参数，请用户根据需要自行构建参数值
                token:
                   1.若用户自行维护token,将用户维护的token赋值给该参数即可
                   2.SDK包中有获取token的函数，请根据接口path在《OpenAPI SDK 总览》文档中查找获取token函数的名字
                     在使用过程中，请注意token互刷问题
                header:
                   sdk中默认填充content-type请求头，若不需要填充除content-type之外的请求头，删除该参数即可
            */
            V2Jscode2sessionRequest sdkRequest = new V2Jscode2sessionRequest();
            sdkRequest.setAnonymousCode(anonymousCode);
            sdkRequest.setAppid("tt767a00c7e971e78301");
            sdkRequest.setCode(code);
            sdkRequest.setSecret("9a05aacc286beaa774ca7d7f4febc33d25359a0d");
            V2Jscode2sessionResponse sdkResponse = client.V2Jscode2session(sdkRequest);
            return sdkResponse;
        } catch (TeaException e) {
            System.out.println(e.getMessage());
            return null;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }
    }

    private AppAuthLoginRespVO createTokenAfterLoginSuccess(MemberUserDO user, String mobile,
                                                            LoginLogTypeEnum logType, String openid) {
        // 插入登陆日志
        createLoginLog(user.getId(), mobile, logType, LoginResultEnum.SUCCESS);
        // 创建 Token 令牌
        OAuth2AccessTokenRespDTO accessTokenRespDTO = oauth2TokenApi.createAccessToken(new OAuth2AccessTokenCreateReqDTO()
                .setUserId(user.getId()).setUserType(getUserType().getValue())
                .setClientId(OAuth2ClientConstants.CLIENT_ID_DEFAULT));
        // 构建返回结果
        return AuthConvert.INSTANCE.convert(accessTokenRespDTO, openid);
    }

    @Override
    public String getSocialAuthorizeUrl(Integer type, String redirectUri) {
        return socialClientApi.getAuthorizeUrl(type, UserTypeEnum.MEMBER.getValue(), redirectUri);
    }

    private MemberUserDO login0(String mobile, String password) {
        final LoginLogTypeEnum logTypeEnum = LoginLogTypeEnum.LOGIN_MOBILE;
        // 校验账号是否存在
        MemberUserDO user = userService.getUserByMobile(mobile);
        if (user == null) {
            createLoginLog(null, mobile, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
            throw exception(AUTH_LOGIN_BAD_CREDENTIALS);
        }
        if (!userService.isPasswordMatch(password, user.getPassword())) {
            createLoginLog(user.getId(), mobile, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
            throw exception(AUTH_LOGIN_BAD_CREDENTIALS);
        }
        // 校验是否禁用
        if (ObjectUtil.notEqual(user.getStatus(), CommonStatusEnum.ENABLE.getStatus())) {
            createLoginLog(user.getId(), mobile, logTypeEnum, LoginResultEnum.USER_DISABLED);
            throw exception(AUTH_LOGIN_USER_DISABLED);
        }
        return user;
    }

    private void createLoginLog(Long userId, String mobile, LoginLogTypeEnum logType, LoginResultEnum loginResult) {
        // 插入登录日志
        LoginLogCreateReqDTO reqDTO = new LoginLogCreateReqDTO();
        reqDTO.setLogType(logType.getType());
        reqDTO.setTraceId(TracerUtils.getTraceId());
        reqDTO.setUserId(userId);
        reqDTO.setUserType(getUserType().getValue());
        reqDTO.setUsername(mobile);
        reqDTO.setUserAgent(ServletUtils.getUserAgent());
        reqDTO.setUserIp(getClientIP());
        reqDTO.setResult(loginResult.getResult());
        loginLogApi.createLoginLog(reqDTO);
        // 更新最后登录时间
        if (userId != null && Objects.equals(LoginResultEnum.SUCCESS.getResult(), loginResult.getResult())) {
            userService.updateUserLogin(userId, getClientIP());
        }
    }

    @Override
    public void logout(String token) {
        // 删除访问令牌
        OAuth2AccessTokenRespDTO accessTokenRespDTO = oauth2TokenApi.removeAccessToken(token);
        if (accessTokenRespDTO == null) {
            return;
        }
        // 删除成功，则记录登出日志
        createLogoutLog(accessTokenRespDTO.getUserId());
    }

    @Override
    public void sendSmsCode(Long userId, AppAuthSmsSendReqVO reqVO) {
        // 情况 1：如果是修改手机场景，需要校验新手机号是否已经注册，说明不能使用该手机了
        if (Objects.equals(reqVO.getScene(), SmsSceneEnum.MEMBER_UPDATE_MOBILE.getScene())) {
            MemberUserDO user = userService.getUserByMobile(reqVO.getMobile());
            if (user != null && !Objects.equals(user.getId(), userId)) {
                throw exception(AUTH_MOBILE_USED);
            }
        }
        // 情况 2：如果是重置密码场景，需要校验手机号是存在的
        if (Objects.equals(reqVO.getScene(), SmsSceneEnum.MEMBER_RESET_PASSWORD.getScene())) {
            MemberUserDO user = userService.getUserByMobile(reqVO.getMobile());
            if (user == null) {
                throw exception(USER_MOBILE_NOT_EXISTS);
            }
        }
        // 情况 3：如果是修改密码场景，需要查询手机号，无需前端传递
        if (Objects.equals(reqVO.getScene(), SmsSceneEnum.MEMBER_UPDATE_PASSWORD.getScene())) {
            MemberUserDO user = userService.getUser(userId);
            // TODO 芋艿：后续 member user 手机非强绑定，这块需要做下调整；
            reqVO.setMobile(user.getMobile());
        }

        // 执行发送
        smsCodeApi.sendSmsCode(AuthConvert.INSTANCE.convert(reqVO).setCreateIp(getClientIP()));
    }

    @Override
    public void validateSmsCode(Long userId, AppAuthSmsValidateReqVO reqVO) {
        smsCodeApi.validateSmsCode(AuthConvert.INSTANCE.convert(reqVO));
    }

    @Override
    public AppAuthLoginRespVO refreshToken(String refreshToken) {
        OAuth2AccessTokenRespDTO accessTokenDO = oauth2TokenApi.refreshAccessToken(refreshToken,
                OAuth2ClientConstants.CLIENT_ID_DEFAULT);
        return AuthConvert.INSTANCE.convert(accessTokenDO, null);
    }

    private void createLogoutLog(Long userId) {
        LoginLogCreateReqDTO reqDTO = new LoginLogCreateReqDTO();
        reqDTO.setLogType(LoginLogTypeEnum.LOGOUT_SELF.getType());
        reqDTO.setTraceId(TracerUtils.getTraceId());
        reqDTO.setUserId(userId);
        reqDTO.setUserType(getUserType().getValue());
        reqDTO.setUsername(getMobile(userId));
        reqDTO.setUserAgent(ServletUtils.getUserAgent());
        reqDTO.setUserIp(getClientIP());
        reqDTO.setResult(LoginResultEnum.SUCCESS.getResult());
        loginLogApi.createLoginLog(reqDTO);
    }

    private String getMobile(Long userId) {
        if (userId == null) {
            return null;
        }
        MemberUserDO user = userService.getUser(userId);
        return user != null ? user.getMobile() : null;
    }

    private UserTypeEnum getUserType() {
        return UserTypeEnum.MEMBER;
    }

}
